import {FlatList, SafeAreaView, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import {ScreenHeader} from "./components/ScreenHeader.tsx";
import React, {useCallback, useState} from "react";
import {getDone, getMySeal, getTodo} from "../../api/seal.ts";
import {SealCard, SealCardViewModel} from "./components/SealCard.tsx";
import {Icon, ListItem} from "@rneui/themed";
import {useFocusEffect, useNavigation} from "@react-navigation/native";
import {useList} from "./hooks/useList.ts";
import dayjs from "dayjs";

const createSealCardViewModel = (item: any, activeTab: string): SealCardViewModel => {
    if (activeTab === '我的用印') {
        return {
            id: item.id,
            title: item.materialName,
            status: item.status,
            personLabel: '经办人',
            personName: item.signers.split("，")[0],
            mainFields: [
                {icon: 'document-text-outline', label: '申请单标题', value: item.applyTitle || '无'},
                {icon: 'barcode-outline', label: '用印编号', value: item.sealNumber || '无'},
                {icon: 'call-outline', label: '联系电话', value: item.phone || '无'},
            ]
        };
    }

    // '待办' 和 '已办' 结构类似
    const applyData = item.applyData || {};
    return {
        id: applyData.id,
        title: applyData.materialName,
        status: applyData.status,
        personLabel: '申请人',
        personName: applyData.signers.split("，")[0],
        mainFields: [
            {icon: 'document-text-outline', label: '申请单标题', value: applyData.applyTitle || '无'},
            {
                icon: 'time-outline',
                label: '申请时间',
                value: applyData.createTime ? dayjs(applyData.createTime).format('YYYY-MM-DD HH:mm') : '无'
            },
            {icon: 'information-circle-outline', label: '当前节点', value: item.name || '无'},
        ]
    };
};

// 列表底部组件，用于显示“加载中”
const ListFooter = ({loading}: { loading: boolean }) => {
    if (!loading) return null;
    return (
        <View style={styles.footer}>
            <ListItem.Content style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}>
                <Icon name="loader" type="feather" size={20} color="#409EFF"/>
                <Text style={{marginLeft: 5, color: '#409EFF'}}>加载中...</Text>
            </ListItem.Content>
        </View>
    );
};

// 可复用的列表组件
const SealList = ({listProps, renderItem}: any) => {
    // 当列表显示时，自动刷新数据
    useFocusEffect(
        useCallback(() => {
            listProps.refresh();
        },[listProps.refresh])
    );

    return (
        <FlatList
            data={listProps.list}
            renderItem={renderItem}
            keyExtractor={(item, index) => `${item.id}-${index}`}
            onEndReached={listProps.loadMore}
            onEndReachedThreshold={0.5}
            ListFooterComponent={<ListFooter loading={listProps.loading}/>}
            onRefresh={listProps.refresh}
            refreshing={listProps.isRefreshing}
        />
    );
};

const styles = StyleSheet.create({
    safeArea: {
        flex: 1,
    },
    tabContainer: {
        flexDirection: 'row',
        justifyContent: 'space-around',
    },
    tabItem: {
        paddingVertical: 15,
        alignItems: 'center',
        flex: 1,
    },
    activeTabItem: {
        borderBottomWidth: 3,
        borderBottomColor: '#2498F7',
    },
    tabText: {
        color: '#333',
        fontSize: 16,
    },
    activeTabText: {
        color: '#2498F7',
        fontWeight: 'bold',
    },
    tabContent: {
        flex: 1,
        marginVertical: 10,
        padding: 5,
    },
    footer: {
        paddingVertical: 20,
    },
});

export function SealScreen(props: any) {
    const [activeTab, setActiveTab] = useState<string>("我的用印");
    const navigation = useNavigation();

    const mySealList = useList(getMySeal);
    const todoSealList = useList(getTodo);
    const doneSealList = useList(getDone);

    const renderItem = useCallback(({item}: { item: any }) => {
        const viewModel = createSealCardViewModel(item, activeTab);
        const navigateToDetail = () => {
            switch (activeTab) {
                case '我的用印':
                    navigation.navigate('MySealDetail', {item: item});
                    break;
                case '待办列表':
                    navigation.navigate('TodoDetail', {item: item});
                    break;
                case '已办列表':
                    navigation.navigate('DoneDetail', {item: item});
                    break;
            }
        };

        return <SealCard item={viewModel} onPress={navigateToDetail}/>;
    }, [activeTab, navigation]);
    // 根据activeTab渲染对应的列表内容
    const renderTabContent = () => {
        switch (activeTab) {
            case '我的用印':
                return <SealList key="我的用印" listProps={mySealList} renderItem={renderItem}/>;
            case '待办列表':
                return <SealList key="待办列表" listProps={todoSealList} renderItem={renderItem}/>;
            case '已办列表':
                return <SealList key="已办列表" listProps={doneSealList} renderItem={renderItem}/>;
            default:
                return null;
        }
    };

    return (
        <SafeAreaView style={styles.safeArea}>
            <ScreenHeader
                navigation={props.navigation}
                title="用印"
                rightText="发起用印申请"
                onRightPress={() => {
                    props.navigation.navigate('CreateSealScreen',{
                        type: "create",
                        id: null
                    });
                }}
            />
            <View style={{flex: 1}}>
                {/*三个可点击的栏*/}
                <View style={styles.tabContainer}>
                    <TouchableOpacity onPress={() => setActiveTab('我的用印')}
                                      style={[styles.tabItem, activeTab === '我的用印' && styles.activeTabItem]}>
                        <Text style={[styles.tabText, activeTab === '我的用印' && styles.activeTabText]}>我的用印</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => setActiveTab('待办列表')}
                                      style={[styles.tabItem, activeTab === '待办列表' && styles.activeTabItem]}>
                        <Text style={[styles.tabText, activeTab === '待办列表' && styles.activeTabText]}>待办列表</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => setActiveTab('已办列表')}
                                      style={[styles.tabItem, activeTab === '已办列表' && styles.activeTabItem]}>
                        <Text style={[styles.tabText, activeTab === '已办列表' && styles.activeTabText]}>已办列表</Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.tabContent}>
                    {renderTabContent()}
                </View>
            </View>
        </SafeAreaView>
    );
}